package com.jhhc.WaterQuality.Calculate.Forecast.util;


import com.jhhc.StormSurgeForecast.AstronomicalTide.Dao.BDMS_FBC_ELEMENTS_BMapper;
import com.jhhc.StormSurgeForecast.StormSurge.Pojo.FBC.BDMS_FBC_ELEMENTS_B;
import com.jhhc.StormSurgeForecast.StormSurge.Pojo.GZABO.Element;
import com.jhhc.StormSurgeForecast.StormSurge.Service.BDMS_FBC_ELEMENTS_BService;
import com.jhhc.WaterQuality.BaseInfo.entity.BDMS_YB_FORECASTSTATION_B;
import com.jhhc.WaterQuality.BaseInfo.service.BDMS_YB_FORECASTSTATION_BService;
import com.jhhc.WaterQuality.Calculate.Forecast.entity.BDMS_CALCULATESCHEME_M;
import com.jhhc.WaterQuality.Calculate.Forecast.entity.BDMS_SLX_RESULT_M;
import com.jhhc.WaterQuality.Calculate.Forecast.service.BDMS_CALCULATESCHEME_MService;
import com.jhhc.WaterQuality.Calculate.Forecast.service.BDMS_SLX_RESULT_MService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.jhhc.BDMS.File.FileUploadController.deleteFolder;

@Service
public class AsyncUtil {
    @Autowired
    private BDMS_CALCULATESCHEME_MService bdms_calculatescheme_mService;
    @Autowired
    private BDMS_SLX_RESULT_MService bdms_slx_result_mService;
    @Resource
    private BDMS_FBC_ELEMENTS_BMapper bdms_fbc_elements_bMapper;
    @Value("${modelPath}")
    String  modelPath;
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Calendar calendar = new GregorianCalendar();
    public  List<String> readFile(String filePath,String sensor,BDMS_CALCULATESCHEME_M bdms_calculatescheme_m,String values1,int len) throws IOException, ParseException {
        DecimalFormat a1 = new DecimalFormat("00000000");
        DecimalFormat a2 = new DecimalFormat("#0000000");
//        filePath = "E:\\work\\DYE_TSK_0_DOM.DAT";
        //  String，Builder stringBuilder = new StringBuilder();
        List<String> list = new ArrayList<>();
        Set<String> uniqueTimeLines = new HashSet<>(); // 用于存储已解析的时间行

        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            StringBuilder stringBuilder = new StringBuilder();
            String tm = null;
            boolean skipDataLine = false; // 标志变量，用于跳过解析数据行

            while ((line = br.readLine()) != null) {
                if (line.length()>11&&"         ** ".equals(line.substring(0, 12))) {
                    System.out.println(line);
                    // stringBuilder = new StringBuilder();
                    tm = line.substring(49, 57).trim();
                    System.out.println(tm);
                    if (uniqueTimeLines.contains(tm)) {
                        // 如果时间行已经解析过，则跳过解析数据行
                        skipDataLine = true;
                    } else {
                        uniqueTimeLines.add(tm);
                        // 重置标志变量，以便解析数据行
                        skipDataLine = false;
                        // stringBuilder = new StringBuilder();
                    }
                    continue;
                }
                if (skipDataLine) {
                    //System.out.println("跳过数据行: " + tm);
                    continue; // 跳过解析数据行
                }
                if ("  ".equals(line.substring(0,2))) {
                    String[] columns = line.split("  ");
                    //System.out.println(columns.length);
                    for (String column : columns) {
                        column = column.trim();
                        if (!column.isEmpty()) {
                            StringBuilder strWithoutDecimal = new StringBuilder();
                            boolean isNegative = strWithoutDecimal.toString().startsWith("-");

                            if (isNegative) {
                                strWithoutDecimal = new StringBuilder(a2.format(Double.parseDouble(column) * 100000L));
                            } else {
                                strWithoutDecimal = new StringBuilder(a1.format(Double.parseDouble(column) * 100000L));
                            }
                            stringBuilder.append(strWithoutDecimal);
                        }
                    }

                }

            }
            if (stringBuilder.length() > 0) {

                int a=0;
                list.add(stringBuilder.toString());
                String str =list.get(0);
                if ("边界值过大，请修改边界值".equals(str)){
                    bdms_calculatescheme_m.setState(2);
                    bdms_calculatescheme_m.setRemark("边界值过大，请修改边界值");
                    //方案入库
                    //bdms_calculatescheme_mService.insert(bdms_calculatescheme_m);
                } else if ("forrtl: error (65): floating invalid".equals(str)) {
                    bdms_calculatescheme_m.setState(2);
                    bdms_calculatescheme_m.setRemark("计算异常");
                    //方案入库
                    //bdms_calculatescheme_mService.insert(bdms_calculatescheme_m);
                } else {
                    bdms_calculatescheme_m.setState(3);
                    bdms_calculatescheme_m.setRemark("计算成功");
                    List<String> list1 = new ArrayList<>();

                    // 每80304字符分割一次
//                    int len = 80304;
                    //int len = 20128;
                    for (int k = 0; k < str.length(); k += len) {
                        String temp = str.substring(k, k + len);
                        System.out.println(temp);
                        list1.add(temp);
                    }

                    System.out.println("listchangdu:"+list1.size());
                    Date date = format.parse(bdms_calculatescheme_m.getDtmstart());
                    for (int z=0;z<list1.size();z++){
                        BDMS_SLX_RESULT_M bdms_slx_result_m = new BDMS_SLX_RESULT_M();
                        String dttp;
                        dttp = values1;
                        bdms_slx_result_m.setDttp(Integer.valueOf(dttp));
                        bdms_slx_result_m.setCschemeid(bdms_calculatescheme_m.getCschemeid());
                        calendar.setTime(date);
                        calendar.add(Calendar.HOUR,+a);
                        bdms_slx_result_m.setDttm(format.format(calendar.getTime()));
                        a++;
                        bdms_slx_result_m.setDatavalues(list1.get(z));
                        //System.out.println(bdms_slx_result_m);
                        System.out.println(bdms_slx_result_m);
                        bdms_slx_result_mService.insert(bdms_slx_result_m);
                    }
                }

            }
            System.out.println("结束");
            //方案入库
          //  bdms_calculatescheme_mService.insert(bdms_calculatescheme_m);
        } catch (IOException e) {
            e.printStackTrace();
        }

// 在此处可以使用解析后的数据 list 进行后续操作
        return list;
    }
    //@Async
    public List<String> RunModel(String startTime , String sensorType, int  hour , String calId , boolean modify, String pser, String qser,
                                 String value, String sy, BDMS_CALCULATESCHEME_M bdms_calculatescheme_m,String values1,
                                 boolean forecastModel,String elementId) throws Exception {
        String sourceFolder = "";
        int len =0;
        int lin24 =0;
        int lin25 =0;
        int lin26 =0;
        String elementNm =null;
        String newLineContent1 = "          "+hour+"    240       0       0      10       0       0       0       0       1      10";
        if (forecastModel){
            sourceFolder =System.getProperty("user.dir")+"/model/EFDC/"+sensorType;
            len = 20128;
            lin24 = 551;
            lin25 = 565;
            lin26 = 580;
            elementNm ="邓楼泵站粗";
            newLineContent1 = "          "+hour+"    240       0       0      10       0       0       0       0       1      10";
        }else {

            System.out.println("flase++++");
            if (bdms_calculatescheme_m.getPid()==230401) {

                sourceFolder = System.getProperty("user.dir") + "/model/EFDC_ALL/" + sensorType;
                len = 80304;
                elementNm = "邓楼泵站细";
                lin24 = 556;
                lin25 = 572;
                lin26 = 589;
                newLineContent1 = "          " + hour + "    1200       0       0      10       0       0       0       0       1      10";
            }else if (bdms_calculatescheme_m.getPid()==240211){
                sourceFolder = System.getProperty("user.dir") + "/model/EFDC_CQ/" + sensorType;
                len = 66016;
                elementNm = "马耳坝水库";
                lin24 = 550;
                lin25 = 566;
                lin26 = 583;
                newLineContent1 = "          " + hour + "    1200       0       0      10       0       0       0       0      1      10";
            }else if (bdms_calculatescheme_m.getPid()==2107){
                sourceFolder =System.getProperty("user.dir")+"/model/EFDC_XMH/"+sensorType;
//                len = 26328;
                len = 327928;
                elementNm ="新孟河";
                lin24 = 554;
                lin25 = 571;
                lin26 = 589;
                newLineContent1 = "          "+hour+"    4320       0       0      10       0       0       0       0       1      10";

            }

        }
        //创建临时文件/TMP/方案id
        String folderPath = System.getProperty("user.dir")+"/Tmp/"+calId+"/"+sensorType;
        File folder = new File(folderPath);

        if (!folder.exists()) {
            if (folder.mkdirs()){
                System.out.println("文件夹创建成功");
                System.out.println("创建的文件夹路径");
                //执行脚本复制文件
                // 执行复制命令
                Process processCp = Runtime.getRuntime().exec("cmd /c robocopy " + sourceFolder + " " + folderPath + " /E");
                //processCp.waitFor();
                // 输出命令行执行结果
                Scanner scanner = new Scanner(processCp.getInputStream()).useDelimiter("\\A");
                String output = scanner.hasNext() ? scanner.next() : "";
                System.out.println(output);
            }else {
                System.out.println("文件夹创建失败");
            }
        }else{
            System.out.println("文件夹已存在");

        }
        // 指定文件路径
        String filePath;
        filePath =folderPath+ "\\EFDC.EE";
        // 指定要修改的行数
        int lineNumber = 3;
        // 指定要修改的内容
        String tm =  startTime.substring(0,10);
        String newLineContent = "DateBase="+tm;
        try {
            // 读取文件
            File file = new File(filePath);
            BufferedReader reader = new BufferedReader(new FileReader(file));
            StringBuilder sb = new StringBuilder();
            String line;
            // 逐行读取文件内容
            int currentLine = 1;
            while ((line = reader.readLine()) != null) {
                if (currentLine == lineNumber) {
                    // 修改指定行的内容
                    sb.append(newLineContent).append("\n");

                } else {
                    sb.append(line).append("\n");
                }
                currentLine++;
            }
            reader.close();
            // 将修改后的内容写回文件
            //先删除文件
            Path path = Paths.get(filePath);
            try {
                Files.delete(path);
                System.out.println("文件已成功删除！");
            } catch (Exception e) {
                System.out.println("文件删除失败。");
            }
            filePath =folderPath+"\\EFDC.EE";
            FileWriter writer = new FileWriter(filePath);
            writer.write(sb.toString());
            writer.close();
            System.out.println("文件修改成功！");
            //修改inp文件

            //如果网格编号不为空

            String  xy =null;
            if (elementId != null){
                BDMS_FBC_ELEMENTS_B element = bdms_fbc_elements_bMapper.getCalDomainInfoDengLou2(230401,elementNm,"7");
                if (element!=null){
                    String [] els = element.getElementxy().split("\\|");
                    xy =els[Integer.parseInt(elementId)-1];
                }


            }
            int currentLineInp = 1;
            filePath =folderPath+"\\efdc.inp";

            File fileInp = new File(filePath);
            BufferedReader readerInp = new BufferedReader(new FileReader(fileInp));
            StringBuilder sbInp = new StringBuilder();
            String lineInp;


            // 逐行读取文件内容
            int lineNumber1 = 196;
            while ((lineInp = readerInp.readLine()) != null) {
                //System.out.println(lineInp);
                if (xy!=null){
                    if (currentLineInp == lin24) {
                        String [] xys = xy.split(",");
                        String x =xys[0];
                        String y =xys[1];
                        String c24 = "     "+x+"     "+y+"  0.0000E+00       0       0       1       0       0       2       0       0       0       0  1.0000E+00  ! SB";
                        sbInp.append(c24).append("\n");
                    }
                    if (currentLineInp == lin25) {
                        String c25 ="         0         0         0         0  ! SB";
                        sbInp.append(c25).append("\n");
                    }
                    if (currentLineInp == lin26) {
                        String c25 ="  ! SB";
                        sbInp.append(c25).append("\n");
                    }
                }
                if (currentLineInp == lineNumber1) {
                    // 修改指定行的内容
                    sbInp.append(newLineContent1).append("\n");
                }
                else {
                    sbInp.append(lineInp).append("\n");
                }

                currentLineInp++;
            }
            readerInp.close();
            // 将修改后的内容写回文件
            FileWriter writerInp = new FileWriter(fileInp);
            writerInp.write(sbInp.toString());
            writerInp.close();
            // 修改指定行的数据

            //修改inp文件
            int currentLineGit = 1;
            filePath =folderPath+"\\Get\\get.inp";

            File fileGit = new File(filePath);
            BufferedReader readerGit = new BufferedReader(new FileReader(fileGit));
            StringBuilder sbGit = new StringBuilder();
            String lineGit;
            String newLineContent3 = folderPath+"\\efdc.inp";

            // 逐行读取文件内容
            int lineNumber3 = 1;
            while ((lineGit = readerGit.readLine()) != null) {

                if (currentLineGit == lineNumber3) {
                    // 修改指定行的内容
                    sbGit.append(newLineContent3).append("\n");
                }
                else {
                    sbGit.append(lineGit).append("\n");
                }

                currentLineGit++;
            }
            readerGit.close();
            // 将修改后的内容写回文件
            FileWriter writerGit = new FileWriter(fileGit);
            writerGit.write(sbGit.toString());
            writerGit.close();
            // 修改指定行的数据
            System.out.println("文件修改成功！");

            //修改水位及流量边界文件
            //从预报结束时间设置
            filePath=folderPath+"\\qser.inp";
            System.out.println(filePath);
            // 读取文件
            File fileQser = new File(filePath);
            BufferedReader readerQser = new BufferedReader(new FileReader(fileQser));
            StringBuilder sbQser = new StringBuilder();
            String newLineContentQser = "          0      "+hour+"   3600       0       1       0       0    !  CG";
            String lineQser;
            lineNumber=15;
            // 逐行读取文件内容
            int currentLineQser = 1;
            while ((lineQser = readerQser.readLine()) != null) {
                if (currentLineQser<16) {
                    if (currentLineQser == lineNumber) {
                        // 修改指定行的内容
                        sbQser.append(newLineContentQser).append("\n");
                    } else {
                        sbQser.append(lineQser).append("\n");
                    }
                }
                currentLineQser++;

            }
            readerQser.close();
            sbQser.append(qser);
            System.out.println(fileQser);
            FileWriter writeQser = new FileWriter(fileQser);
            writeQser.write(sbQser.toString());
            writeQser.close();
            // 修改指定行的数据
            System.out.println("流量边界文件修改成功！");
            //修改水位及流量边界文件
            //从预报结束时间设置
            filePath=folderPath+"\\pser.inp";
            System.out.println(filePath);
            // 读取文件
            File filePser = new File(filePath);
            BufferedReader readerPser = new BufferedReader(new FileReader(filePser));
            StringBuilder sbPser = new StringBuilder();
            String newLineContentPser = "         0       "+hour+"   3600       0       1       0       0  !  BLW";
            String linePser;
            int lineNumberPser=11;
            // 逐行读取文件内容
            int currentLinePser = 1;
            while ((linePser = readerPser.readLine()) != null) {
                //if (currentLineSY<41){
                if (currentLinePser == lineNumberPser) {
                    // 修改指定行的内容
                    sbPser.append(newLineContentPser).append("\n");
                } else {
                    sbPser.append(linePser).append("\n");
                }
                currentLinePser++;
                // }


            }
            readerPser.close();
            sbPser.append(pser);
            System.out.println(filePser);
            FileWriter writePser = new FileWriter(filePser);
            writePser.write(sbPser.toString());
            writePser.close();
            // 修改指定行的数据
            System.out.println("水位边界文件修改成功！");
            //修改写入qser.inp
            ///如果不为空则数据拼接给值
            if ("SY".equals(sensorType)){
                filePath=folderPath+"\\dser.inp";
                // 读取文件
                File fileSY = new File(filePath);
                BufferedReader readerSY = new BufferedReader(new FileReader(fileSY));
                StringBuilder sbSY = new StringBuilder();
                String lineSY;
                String newLineContent4 = "          0       "+hour+"   3600       0       1        0   !  "+sensorType;
                lineNumber=40;
                // 逐行读取文件内容
                int currentLineSY = 1;
                while ((lineSY = readerSY.readLine()) != null) {
                    if (currentLineSY<41){
                        if (currentLineSY == lineNumber) {
                            // 修改指定行的内容
                            sbSY.append(newLineContent4).append("\n");
                        } else {
                            sbSY.append(lineSY).append("\n");
                        }
                        currentLineSY++;
                    }
                }
                readerSY.close();
                sbSY.append(sy);
//                String [] values = value.split(",");
//                // System.out.println(values);
//                for (int i=0;i<values.length;i++){
//
//                    sbSY.append("     ").append(i).append(".000    ").append(values[i]).append("\n");
//                    System.out.println(values[i].trim());
//                }

                FileWriter writerSY = new FileWriter(fileSY);
                writerSY.write(sbSY.toString());
                writerSY.close();

            }else {
                System.out.println("dser"+value);
                filePath=folderPath+"\\dser.inp";
                // 读取文件
                File fileSY = new File(filePath);
                BufferedReader readerSY = new BufferedReader(new FileReader(fileSY));
                StringBuilder sbSY = new StringBuilder();
                String newLineContent4 = "          0       "+hour+"   3600       0       1        0   !  "+sensorType;
                String lineSY;
                lineNumber=40;
                // 逐行读取文件内容
                int currentLineSY = 1;
                while ((lineSY = readerSY.readLine()) != null) {
                    if (currentLineSY<41){
                        if (currentLineSY == lineNumber) {
                            // 修改指定行的内容
                            sbSY.append(newLineContent4).append("\n");
                        } else {
                            sbSY.append(lineSY).append("\n");
                        }
                        currentLineSY++;
                    }
                }
                readerSY.close();
                sbSY.append(value);
                FileWriter writerSY = new FileWriter(fileSY);
                writerSY.write(sbSY.toString());
                writerSY.close();
                // 修改指定行的数据
                System.out.println(sensorType+"文件修改成功！");
            }


            //更新bat
            filePath = folderPath + "\\0_RunEFDC1.Bat";

            File fileRun = new File(filePath);
            BufferedReader readerRun = new BufferedReader(new FileReader(fileRun));
            StringBuilder sbRun = new StringBuilder();
            String newLineContentRun = "SET KMP_AFFINITY=granularity=fine,compact,1,0 & "+modelPath+"\\EFDC_DSI_071_SGL_130823.exe -NT1" ;
            String lineRun;
            lineNumber=1;
            int currentLineRun= 1;
            while ((lineRun = readerRun.readLine()) != null) {

                // 修改指定行的内容
                if (lineNumber==currentLineRun){
                    sbRun.append(newLineContentRun).append("\n");
                }else {
                    sbRun.append(lineRun).append("\n");
                }

                currentLineRun++;

            }
            readerRun.close();
            FileWriter writerRun = new FileWriter(fileRun);
            System.out.println("gengxinbat"+sbRun);
            writerRun.write(sbRun.toString());
            writerRun.close();


            ProcessBuilder processBuilder = new ProcessBuilder(filePath);
            processBuilder.directory(new File(folderPath));
            Process process = processBuilder.start();
            InputStream inputStream = process.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));


            // 读取第一行
            String firstLine = bufferedReader.readLine();
            // 继续读取下一行
            String text = bufferedReader.readLine();

            int res =0;
            for (; text != null; text = bufferedReader.readLine()) {

                if ("".equals(text)) {
                    res++;
                }
                if (" NEG DEPTH AT CELL CENTER".equals(text)){
                    List<String> result = new ArrayList<>();
                    result.add("边界值过大，请修改边界值");
                    return  result;
                }
                if ("forrtl: error (65): floating invalid".equals(text)){
                    List<String> result = new ArrayList<>();
                    result.add("计算异常");
                    return  result;
                }

                if (res ==2){
                    Process processK = Runtime.getRuntime().exec("taskkill /f /im \"EFDC_DSI_071_SGL_130823.exe\"");
                    InputStream inputStreamK = processK.getInputStream();
                    BufferedReader bufferedReaderK = new BufferedReader(new InputStreamReader(inputStreamK));
                    String text1;
                    while ((text1 = bufferedReaderK.readLine()) != null) {
                        text =text1;
                    }
                }

            }
            bufferedReader.close();
            process.destroy();
            System.out.println(".bat文件执行成功！");

            //更新gitinpwenjian
            //  调用执行get.bat
            filePath = folderPath + "\\Get\\get.bat";

            ProcessBuilder processBuilder1 = new ProcessBuilder(filePath);
            processBuilder1.directory(new File( folderPath + "\\Get"));
            Process process1 = processBuilder1.start();
            InputStream inputStream1 = process1.getInputStream();

            BufferedReader bufferedReader1 = new BufferedReader(new InputStreamReader(inputStream1));
            String text1;
            while ((text1 = bufferedReader1.readLine()) != null) {
                // System.out.println("shuchu:" + text1);
                if ("Fortran Pause - Enter command<CR> or <CR> to continue.".equals(text1)) {
                    break;
                }
            }
            //解析数据文件入库
            return  readFile(folderPath+"\\#output\\DYE_TSK_0_DOM.DAT",sensorType,bdms_calculatescheme_m,values1,len);

        } catch (Exception e) {
            System.out.println("程序异常：" + e.getLocalizedMessage());
            e.printStackTrace();
        }
        return null;
    }


//    @Async
    public List<String> RunModel2(String startTime , String sensorType, int  hour , String calId , boolean modify, String pser, String qser,
                                 String value, String sy, BDMS_CALCULATESCHEME_M bdms_calculatescheme_m,String values1,
                                 boolean forecastModel,String elementId) throws Exception {
        String sourceFolder = "";
        int len =0;
        int lineNumber2 =0;
        int lin24 =0;
        int lin25 =0;
        int lin26 =0;
        int lin72 =0;
        int lin73 =0;
        int linDser =0;
        String elementNm =null;
        String newLineContent1 = "          "+hour+"    240       0       0      10       0       0       0       0       1      10";
        String newLineContent2 = "          "+1+"    240       0       0      10       0       0       0       0       1      10";
        if (forecastModel){
            sourceFolder =System.getProperty("user.dir")+"/model/EFDC/"+sensorType;
            len = 20128;
            lin24 = 551;
            lin25 = 565;
            lin26 = 580;
            linDser=40;
            elementNm ="邓楼泵站粗";
            newLineContent1 = "          "+hour+"    240       0       0      10       0       0       0       0       1      10";
        }else {

            System.out.println("flase++++");
            if (bdms_calculatescheme_m.getPid()==230401) {
                linDser = 40;
                sourceFolder = System.getProperty("user.dir") + "/model/EFDC_ALL/" + sensorType;
                len = 80304;
                elementNm = "邓楼泵站细";
                lin24 = 556;
                lin25 = 572;
                lin26 = 589;
                newLineContent1 = "          " + hour + "    1200       0       0      10       0       0       0       0       1      10";
            }else if (bdms_calculatescheme_m.getPid()==240211){
                sourceFolder = System.getProperty("user.dir") + "/model/EFDC_CQ/" + sensorType;
                len = 66016;
                elementNm = "马耳坝水库";
                lin24 = 550;
                lin25 = 566;
                lin26 = 583;
                newLineContent1 = "          " + hour + "    1200       0       0      10       0       0       0       0      1      10";
            }else if (bdms_calculatescheme_m.getPid()==2107){
                sourceFolder =System.getProperty("user.dir")+"/model/EFDC_XMH/"+sensorType;
//                len = 26328;
                len = 327928;
                elementNm ="新孟河";
                lineNumber2 = 213;
                lin24 = 554;
                lin25 = 571;
                lin26 = 589;
                lin72 = 1592;
                lin73 = 1607;
                linDser = 16;
                Long aa= (long) (hour * 360L);
                newLineContent1 = "          "+1+"    "+aa+"       0       0      10       0       0       0       0       1      10";
                newLineContent2 = "        86400         0    "+aa+"0         0         0         1         1         1         0         0";
            }

        }
        //创建临时文件/TMP/方案id
        String folderPath = System.getProperty("user.dir")+"/Tmp/"+calId+"/"+sensorType;
        File folder = new File(folderPath);

        if (!folder.exists()) {
            if (folder.mkdirs()){
                System.out.println("文件夹创建成功");
                System.out.println("创建的文件夹路径");
                //执行脚本复制文件
                // 执行复制命令
                Process processCp = Runtime.getRuntime().exec("cmd /c robocopy " + sourceFolder + " " + folderPath + " /E");
                //processCp.waitFor();
                // 输出命令行执行结果
                Scanner scanner = new Scanner(processCp.getInputStream()).useDelimiter("\\A");
                String output = scanner.hasNext() ? scanner.next() : "";
                System.out.println(output);
            }else {
                System.out.println("文件夹创建失败");
            }
        }else{
            System.out.println("文件夹已存在");

        }
        // 指定文件路径
        String filePath;
        filePath =folderPath+ "\\EFDC.EE";
        // 指定要修改的行数
        int lineNumber = 3;
        // 指定要修改的内容
        String tm =  startTime.substring(0,10);
        String newLineContent = "DateBase="+tm;
        try {
            // 读取文件
            File file = new File(filePath);
            BufferedReader reader = new BufferedReader(new FileReader(file));
            StringBuilder sb = new StringBuilder();
            String line;
            // 逐行读取文件内容
            int currentLine = 1;
            while ((line = reader.readLine()) != null) {
                if (currentLine == lineNumber) {
                    // 修改指定行的内容
                    sb.append(newLineContent).append("\n");

                } else {
                    sb.append(line).append("\n");
                }
                currentLine++;
            }
            reader.close();
            // 将修改后的内容写回文件
            //先删除文件
            Path path = Paths.get(filePath);
            try {
                Files.delete(path);
                System.out.println("文件已成功删除！");
            } catch (Exception e) {
                System.out.println("文件删除失败。");
            }
            filePath =folderPath+"\\EFDC.EE";
            FileWriter writer = new FileWriter(filePath);
            writer.write(sb.toString());
            writer.close();
            System.out.println("文件修改成功！");
            //修改inp文件

            //如果网格编号不为空

            String  xy =null;
            if (elementId != null){
                BDMS_FBC_ELEMENTS_B element = bdms_fbc_elements_bMapper.getCalDomainInfoDengLou2(230401,elementNm,"7");
                if (element!=null){
                    String [] els = element.getElementxy().split("\\|");
                    xy =els[Integer.parseInt(elementId)-1];
                }


            }
            int currentLineInp = 1;
            filePath =folderPath+"\\efdc.inp";

            File fileInp = new File(filePath);
            BufferedReader readerInp = new BufferedReader(new FileReader(fileInp));
            StringBuilder sbInp = new StringBuilder();
            String lineInp;


            // 逐行读取文件内容
            int lineNumber1 = 196;
            while ((lineInp = readerInp.readLine()) != null) {
                //System.out.println(lineInp);
                if (xy!=null){
                    if (currentLineInp == lin24) {
                        String [] xys = xy.split(",");
                        String x =xys[0];
                        String y =xys[1];
                        String c24 = "     "+x+"     "+y+"  0.0000E+00       0       0       1       0       0       2       0       0       0       0  1.0000E+00  ! SB";
                        sbInp.append(c24).append("\n");
                    }
                    if (currentLineInp == lin25) {
                        String c25 ="         0         0         0         0  ! SB";
                        sbInp.append(c25).append("\n");
                    }
                    if (currentLineInp == lin26) {
                        String c25 ="  ! SB";
                        sbInp.append(c25).append("\n");
                    }

                }
                if (currentLineInp == lineNumber1) {
                    // 修改指定行的内容
                    sbInp.append(newLineContent1).append("\n");
                }

                else {
                    if (lineNumber2 >0 && currentLineInp == lineNumber2) {
                        // 修改指定行的内容
                        sbInp.append(newLineContent2).append("\n");
                    }
                    if  (lin72>0){
                        String c723 ="          1      "+hour+"       0       3";
                        if (currentLineInp == lin72) {
                            sbInp.append(c723).append("\n");
                        }
                        if (currentLineInp == lin73) {
                            sbInp.append(c723).append("\n");
                        }
                    }
                    sbInp.append(lineInp).append("\n");
                }

                currentLineInp++;
            }
            readerInp.close();
            // 将修改后的内容写回文件
            FileWriter writerInp = new FileWriter(fileInp);
            writerInp.write(sbInp.toString());
            writerInp.close();
            // 修改指定行的数据

            //修改inp文件
            int currentLineGit = 1;
            filePath =folderPath+"\\Get\\get.inp";

            File fileGit = new File(filePath);
            BufferedReader readerGit = new BufferedReader(new FileReader(fileGit));
            StringBuilder sbGit = new StringBuilder();
            String lineGit;
            String newLineContent3 = folderPath+"\\efdc.inp";

            // 逐行读取文件内容
            int lineNumber3 = 1;
            while ((lineGit = readerGit.readLine()) != null) {

                if (currentLineGit == lineNumber3) {
                    // 修改指定行的内容
                    sbGit.append(newLineContent3).append("\n");
                }
                else {
                    sbGit.append(lineGit).append("\n");
                }

                currentLineGit++;
            }
            readerGit.close();
            // 将修改后的内容写回文件
            FileWriter writerGit = new FileWriter(fileGit);
            writerGit.write(sbGit.toString());
            writerGit.close();
            // 修改指定行的数据
            System.out.println("文件修改成功！");

            //修改水位及流量边界文件
            //从预报结束时间设置
            filePath=folderPath+"\\qser.inp";
            System.out.println(filePath);
            // 读取文件
            File fileQser = new File(filePath);
            BufferedReader readerQser = new BufferedReader(new FileReader(fileQser));
            StringBuilder sbQser = new StringBuilder();
            String newLineContentQser = "          0      "+hour+"   3600       0       1       0       0    !  CG";
            String lineQser;
            lineNumber=15;
            // 逐行读取文件内容
            int currentLineQser = 1;
            while ((lineQser = readerQser.readLine()) != null) {
                if (currentLineQser<16) {
                    if (currentLineQser == lineNumber) {
                        // 修改指定行的内容
                        sbQser.append(newLineContentQser).append("\n");
                    } else {
                        sbQser.append(lineQser).append("\n");
                    }
                }
                currentLineQser++;

            }
            readerQser.close();
            sbQser.append(qser);
            System.out.println(fileQser);
            FileWriter writeQser = new FileWriter(fileQser);
            writeQser.write(sbQser.toString());
            writeQser.close();
            // 修改指定行的数据
            System.out.println("流量边界文件修改成功！");
            //修改水位及流量边界文件
            //从预报结束时间设置
            filePath=folderPath+"\\pser.inp";
            System.out.println(filePath);
            // 读取文件
            File filePser = new File(filePath);
            BufferedReader readerPser = new BufferedReader(new FileReader(filePser));
            StringBuilder sbPser = new StringBuilder();
            String newLineContentPser = "         0       "+hour+"   3600       0       1       0       0  !  BLW";
            String linePser;
            int lineNumberPser=11;
            // 逐行读取文件内容
            int currentLinePser = 1;
            while ((linePser = readerPser.readLine()) != null) {
                //if (currentLineSY<41){
                if (currentLinePser == lineNumberPser) {
                    // 修改指定行的内容
                    sbPser.append(newLineContentPser).append("\n");
                } else {
                    sbPser.append(linePser).append("\n");
                }
                currentLinePser++;
                // }


            }
            readerPser.close();
            sbPser.append(pser);
            System.out.println(filePser);
            FileWriter writePser = new FileWriter(filePser);
            writePser.write(sbPser.toString());
            writePser.close();
            // 修改指定行的数据
            System.out.println("水位边界文件修改成功！");
            //修改写入qser.inp
            ///如果不为空则数据拼接给值
            if ("SY".equals(sensorType)){
                filePath=folderPath+"\\dser.inp";
                // 读取文件
                File fileSY = new File(filePath);
                BufferedReader readerSY = new BufferedReader(new FileReader(fileSY));
                StringBuilder sbSY = new StringBuilder();
                String lineSY;
                String newLineContent4 = "          0       "+hour+"   3600       0       1        0   !  "+sensorType;
                lineNumber=40;
                // 逐行读取文件内容
                int currentLineSY = 1;
                while ((lineSY = readerSY.readLine()) != null) {
                    if (currentLineSY<41){
                        if (currentLineSY == lineNumber) {
                            // 修改指定行的内容
                            sbSY.append(newLineContent4).append("\n");
                        } else {
                            sbSY.append(lineSY).append("\n");
                        }
                        currentLineSY++;
                    }
                }
                readerSY.close();
                sbSY.append(sy);
//                String [] values = value.split(",");
//                // System.out.println(values);
//                for (int i=0;i<values.length;i++){
//
//                    sbSY.append("     ").append(i).append(".000    ").append(values[i]).append("\n");
//                    System.out.println(values[i].trim());
//                }

                FileWriter writerSY = new FileWriter(fileSY);
                writerSY.write(sbSY.toString());
                writerSY.close();

            }else {
                System.out.println("dser"+value);
                filePath=folderPath+"\\dser.inp";
                // 读取文件
                File fileSY = new File(filePath);
                BufferedReader readerSY = new BufferedReader(new FileReader(fileSY));
                StringBuilder sbSY = new StringBuilder();
                String newLineContent4 = "          0       "+hour+"   3600       0       1        0   !  "+sensorType;
                String lineSY;
                // 逐行读取文件内容
                int currentLineSY = 1;
                while ((lineSY = readerSY.readLine()) != null) {
                    if (currentLineSY<linDser+1){
                        if (currentLineSY == linDser && linDser!=16) {
                            // 修改指定行的内容
                            sbSY.append(newLineContent4).append("\n");
                        } else {
                            sbSY.append(lineSY).append("\n");
                        }
                        currentLineSY++;
                    }
                }
                readerSY.close();
                sbSY.append(value);
                FileWriter writerSY = new FileWriter(fileSY);
                writerSY.write(sbSY.toString());
                writerSY.close();
                // 修改指定行的数据
                System.out.println(sensorType+"文件修改成功！");
            }


            //更新bat
            filePath = folderPath + "\\0_RunEFDC1.Bat";

            File fileRun = new File(filePath);
            BufferedReader readerRun = new BufferedReader(new FileReader(fileRun));
            StringBuilder sbRun = new StringBuilder();
            String newLineContentRun = "SET KMP_AFFINITY=granularity=fine,compact,1,0 & "+modelPath+"\\EFDC_DSI_071_SGL_130823.exe -NT1" ;
            String lineRun;
            lineNumber=1;
            int currentLineRun= 1;
            while ((lineRun = readerRun.readLine()) != null) {

                // 修改指定行的内容
                if (lineNumber==currentLineRun){
                    sbRun.append(newLineContentRun).append("\n");
                }else {
                    sbRun.append(lineRun).append("\n");
                }

                currentLineRun++;

            }
            readerRun.close();
            FileWriter writerRun = new FileWriter(fileRun);
            System.out.println("gengxinbat"+sbRun);
            writerRun.write(sbRun.toString());
            writerRun.close();


            ProcessBuilder processBuilder = new ProcessBuilder(filePath);
            processBuilder.directory(new File(folderPath));
            Process process = processBuilder.start();
            InputStream inputStream = process.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));


            // 读取第一行
            String firstLine = bufferedReader.readLine();
            // 继续读取下一行
            String text = bufferedReader.readLine();

            int res =0;
            for (; text != null; text = bufferedReader.readLine()) {

                if ("".equals(text)) {
                    res++;
                }
                if (" NEG DEPTH AT CELL CENTER".equals(text)){
                    List<String> result = new ArrayList<>();
                    result.add("边界值过大，请修改边界值");
                    return  result;
                }
                if ("forrtl: error (65): floating invalid".equals(text)){
                    List<String> result = new ArrayList<>();
                    result.add("计算异常");
                    return  result;
                }

                if (res ==2){
                    Process processK = Runtime.getRuntime().exec("taskkill /f /im \"EFDC_DSI_071_SGL_130823.exe\"");
                    InputStream inputStreamK = processK.getInputStream();
                    BufferedReader bufferedReaderK = new BufferedReader(new InputStreamReader(inputStreamK));
                    String text1;
                    while ((text1 = bufferedReaderK.readLine()) != null) {
                        text =text1;
                    }
                }

            }
            bufferedReader.close();
            process.destroy();
            System.out.println(".bat文件执行成功！");

            //更新gitinpwenjian
            //  调用执行get.bat
            filePath = folderPath + "\\Get\\get.bat";

            ProcessBuilder processBuilder1 = new ProcessBuilder(filePath);
            processBuilder1.directory(new File( folderPath + "\\Get"));
            Process process1 = processBuilder1.start();
            InputStream inputStream1 = process1.getInputStream();

            BufferedReader bufferedReader1 = new BufferedReader(new InputStreamReader(inputStream1));
            String text1;
            while ((text1 = bufferedReader1.readLine()) != null) {
                // System.out.println("shuchu:" + text1);
                if ("Fortran Pause - Enter command<CR> or <CR> to continue.".equals(text1)) {
                    break;
                }
            }
            //解析数据文件入库

            System.out.println("解析数据入库");
            List<String> values =  readFile(folderPath+"\\#output\\DYE_TSK_0_DOM.DAT",sensorType,bdms_calculatescheme_m,values1,len);
            if (values!=null&& !values.isEmpty()) {
                String str = values.get(0);
                if ("边界值过大，请修改边界值".equals(str)) {
                    bdms_calculatescheme_m.setState(2);
                    bdms_calculatescheme_m.setRemark("边界值过大，请修改边界值");
                } else if ("forrtl: error (65): floating invalid".equals(str)) {
                    bdms_calculatescheme_m.setState(2);
                    bdms_calculatescheme_m.setRemark("计算异常");
                }else {
                    bdms_calculatescheme_m.setState(3);
                    bdms_calculatescheme_m.setRemark("计算成功");
                }
            }
            System.out.println("values:"+values.size());
            System.out.println(bdms_calculatescheme_m);
            bdms_calculatescheme_mService.insert(bdms_calculatescheme_m);
            //删除文件folderPath
            //deleteFolder(folderPath);
        } catch (Exception e) {
            System.out.println("程序异常：" + e.getLocalizedMessage());
            e.printStackTrace();
        }
        return null;
    }



}
